<template>
  <div>
    <van-dropdown-menu>
      <van-dropdown-item :title="selectedDepartment" ref="itemRef">
        <div class="department-container">
          <div
            v-for="(department, index) in departments"
            :key="index"
            class="department-item"
            :class="{ selected: selectedIndex === index }"
            @click="selectDepartment(index)"
          >
            {{ department }}
          </div>
        </div>
        <div class="select-btn-container">
          <van-button type="text" style="width: 50%" @click="onCancel">取消</van-button>
          <van-button type="primary" style="width: 50%" @click="onConfirm">确认</van-button>
        </div>
      </van-dropdown-item>

      <van-dropdown-item v-model="sortValue" :options="sortOptions" />
    </van-dropdown-menu>

    <!-- 加载状态 -->
    <van-empty v-if="loading" description="加载中..." />
    <van-empty v-if="!loading && doctors.length === 0" description="暂无医生数据" />

    <div v-else v-for="doctor in doctors" :key="doctor.workId" class="card" @click="goToDoctorDetails(doctor.workId)">
      <img :src="doctor.imgUrl" :alt="doctor.doctorName" />
      <div class="card-content">
        <div class="card-header">
          <h3>
            {{ doctor.doctorName }}
            <span class="badge">{{ doctor.title }}</span>
            <span class="gender-tag">{{ doctor.gender }}</span>
          </h3>
        </div>
        <div class="details">{{ doctor.departmentName }}</div>
        <div class="good-at">
          擅长：{{ doctor.personalProfile || '暂无描述' }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useUserStore } from "../stores/user.js";
import { getAllDepartmentNames } from "../api/department/departmentRequest.js";
import { getDoctorsByDepartment } from "../api/doctor/doctorRequest.js";
import { showToast } from 'vant';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 科室相关
const departments = ref(["全部"]);
const selectedDepartment = ref("全部");
const selectedIndex = ref(0);
const oldSelectedIndex = ref(0);
const itemRef = ref(null);

// 排序相关
const sortValue = ref("default");
const sortOptions = [
  { text: "默认排序", value: "default" },
  { text: "好评优先", value: "rating" },
  { text: "预约量优先", value: "appointment" },
];

// 加载状态
const loading = ref(true);

// 医生列表
const doctors = ref([]);

// 获取科室列表
const fetchDepartments = async () => {
  try {
    const res = await getAllDepartmentNames();
    if (res.success) {
      departments.value = ["全部", ...res.data];
      
      // 如果路由中带有科室参数，则设置为选中状态
      if (route.query.department) {
        const index = departments.value.findIndex(
          dept => dept === route.query.department
        );
        if (index !== -1) {
          selectedIndex.value = index;
          selectedDepartment.value = departments.value[index];
        }
      }
    } else {
      showToast(res.errMsg || '获取科室列表失败');
    }
  } catch (error) {
    console.error("获取科室列表失败:", error);
    showToast('获取科室列表失败，请稍后重试');
  }
};

// 获取医生列表
const fetchDoctors = async () => {
  loading.value = true;
  try {
    const res = await getDoctorsByDepartment(selectedDepartment.value);
    if (res.success) {
      doctors.value = res.data.map(doctor => ({
        ...doctor,
        imgUrl: doctor.imgUrl || 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg' // 设置默认头像
      }));
    } else {
      showToast(res.errMsg || '获取医生列表失败');
    }
  } catch (error) {
    console.error("获取医生列表失败:", error);
    showToast('获取医生列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 选择科室
const selectDepartment = (index) => {
  selectedIndex.value = index;
  selectedDepartment.value = departments.value[index];
};

// 取消选择
const onCancel = () => {
  itemRef.value.toggle();
  selectedDepartment.value = departments.value[oldSelectedIndex.value];
  selectedIndex.value = oldSelectedIndex.value;
};

// 确认选择
const onConfirm = () => {
  itemRef.value.toggle();
  oldSelectedIndex.value = selectedIndex.value;
  fetchDoctors(); // 重新获取医生列表
};

// 跳转到医生详情
const goToDoctorDetails = (doctorId) => {
  router.push({
    path: "/doctorDetails",
    query: { id: doctorId }
  });
};

// 监听排序变化
watch(sortValue, () => {
  fetchDoctors();
});

// 组件挂载时初始化数据
onMounted(async () => {
  await fetchDepartments();
  // 如果路由中带有科室参数，则先设置科室，再获取医生列表
  if (route.query.department) {
    const index = departments.value.findIndex(
      dept => dept === route.query.department
    );
    if (index !== -1) {
      selectedIndex.value = index;
      selectedDepartment.value = departments.value[index];
    }
  }
  fetchDoctors();
});
</script>

<style scoped>
.department-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  margin: 20px;
}

.department-item {
  text-align: center;
  font-size: 12px;
  padding: 10px;
  border-radius: 20px;
  background: #f0f0f0;
  color: #333;
  border: 1px solid #ddd;
  cursor: pointer;
  transition: all 0.3s;
}

.department-item:hover {
  background: #e0f7ff;
}

.department-item.selected {
  background: #1e90ff;
  color: white;
  border-color: #1e90ff;
}

.card {
  display: flex;
  background: #fff;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.card img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-right: 15px;
  object-fit: cover;
}

.card-content {
  flex: 1;
}

.card-header {
  display: flex;
  align-items: center;
}

.card-header h3 {
  font-size: 16px;
  margin: 0;
}

.badge {
  display: inline-block;
  background-color: #f9c53f;
  color: #fff;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  margin-left: 5px;
}

.gender-tag {
  display: inline-block;
  background-color: #e8f4ff;
  color: #409eff;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  margin-left: 5px;
}

.details {
  font-size: 14px;
  color: #666;
  margin: 5px 0;
}

.good-at {
  font-size: 13px;
  color: #999;
  line-height: 1.5;
}
</style>
